package com.seaside.park.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.seaside.common.bean.Result;
import com.seaside.parkCommon.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/WeiXinApi")
@Slf4j
public class WeiXinApi {

    @Value("${weixin.appId}")
    private String appId;
    @Value("${weixin.secret}")
    private String secret;


    @ResponseBody
    @RequestMapping(value = "/getToken", produces = "application/json;charset=UTF-8")
    public Result<String> getToken() throws UnsupportedEncodingException {
        Object access = HttpUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+secret);
        JSONObject jsonObject =  JSONObject.parseObject(access.toString());
        if(jsonObject!=null)
        {
            return Result.OK("获取成功!",jsonObject.get("access_token"));
        }else{
            return Result.Error("获取失败!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getOpenId", produces = "application/json;charset=UTF-8")
    public Result<String> getOpenId(String jscode) throws UnsupportedEncodingException {
        Object access = HttpUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+ secret + "&js_code=" + jscode +"&grant_type=authorization_code");
        JSONObject jsonObject =  JSONObject.parseObject(access.toString());
        if(jsonObject!=null)
        {
            return Result.OK("获取成功!",jsonObject.get("openid"));
        }else{
            return Result.Error("获取失败!");
        }
    }


}